import socket, threading,time

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('0.0.0.0',9999))
s.listen(5)
print("Waiting connection...")

def tcplink(sock,addr):
    print('Accept new connection from %s:%s...' %addr)
    sock.send(b'Welcome!')
    while 1:
        data = sock.recv(1024)
        mail = data.decode('utf-8')
        if mail != '':
            print(mail)
            with open('MailList.txt','a') as f:
                f.write(mail + '\n')
        time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            print('Connection from %s:%s closed'%addr)
            break
        sock.send(b'Done!')
    sock.close()

while 1:
    sock,addr = s.accept()
    choice = sock.recv(1024)
    if choice ==  b'names':
        t = threading.Thread(target=tcplink, args=(sock,addr))
        t.start()
    elif choice == b'stop':
        sock.close()
        break
print("server is closing...")
time.sleep(2)